<?php
namespace control;
/*
*招聘计划类
*/

class recruitmentPlanClass extends adIndexClass
{
    private const page = 'recruitmentPlan';
    private const table = 'recruitment_plan';
    private const tableMx = 'recruitment_plan_detail';
    private const title = '招聘计划';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('recruitment.table.orderNo') => text(array("name" => "orderNo")),
                    L('recruitment.table.members')     => selectMultiple(array("name" => "teamStid", "title" => '请选择', "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                    L('recruitment.table.prepared') => selectMultiple(array("name" => "stid", "title" => '请选择', "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                ],
                [
                    L('recruitment.table.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('recruitment.table.state') => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html = $this->homeOptions(false);
        //控件
        $url = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('recruitment.table.addNew') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('recruitment.table.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => L('recruitment.table.orderNo'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'members' => [
                        'name'  => L('recruitment.table.members'),
                        'width' => 300,
                    ],
                    'channel'  => [
                        'name'  => L('recruitment.table.channel'),
                        'width' => 200,
                    ],
                    'money'         => [
                        'name'  => L('recruitment.table.budget'). "(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'prepared'          => [
                        'name'  => L('recruitment.table.prepared'),
                        'width' => 200,
                    ],
                    'time'        => [
                        'name'  => L('recruitment.table.createTime'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => L('recruitment.table.state'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "teamStid" => $this->post('teamStid'),//招聘组成员
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid" => $this->post('stid'),//申请人

        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state'] == '草稿' ? array("title" => L('recruitment.table.edit'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})") : [],
                "detail" => array("title" => L('recruitment.table.planInfo'), "click" => "newIframe('" . L('recruitment.table.planInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "members":
                        $row[] = $this->findTeamStName($array['teamStid']);
                        break;
                    case "prepared":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => $totalQuery['money'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . space . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取招聘组成员姓名
     * @param $teamStid
     * @return string
     */
    public function findTeamStName($teamStid): string
    {
        $staffText = '';
        $staffArr = explode(',', $teamStid);
        foreach ($staffArr as $stid) {
            $staffText .= ',' . self::findStaff($stid);
        }
        return $staffText ? ltrim($staffText, ',') : '';
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('recruitment.table.members') . "：" => selectMultiple([
                        "name" => "teamStid[]", "title" => L('recruitment.table.choose'),
                        'value' => $info['teamStid'],
                        'multiple' => true,
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                        'where' => " state in ('转正','试用','留职')"
                    ]),
                    L('recruitment.table.startAndEnd') . "：" => text(["name" => "chooseDate", 'class' => 'select', 'laydate' => ['range' => '~'], "value" => strtotime($info['startDate']) ? ($info['startDate'] . ' ~ ' . $info['endDate']) : '']),
                ],
                [
                    must . L('recruitment.table.channel') . "：" => select(["name" => "channel", 'title' => L('recruitment.table.channel'), 'class' => 'select', 'option' => explode('，', para('recruitChannel')), "value" => $info['channel']]),
                    must . L('recruitment.table.budget') . "：" => text(["name" => "money", 'unit' =>  static::$unit , "value" => $info['money']])
                ],
                [
                    L('recruitment.table.programme') . "：" => textarea(["name" => "plan", "value" => $info['plan']])
                ],
                [
                    L('recruitment.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor'), "height" => 300, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $timeArr = $this->post('chooseDate') ? explode(' ~ ', $this->post('chooseDate')) : [];
        $field = [
            'teamStid' => $this->post('teamStid') ? implode(',', $this->post('teamStid')) : '',
            'money' => $this->post('money'),
            'startDate' => $timeArr[0] ?? '',
            'endDate' => $timeArr[1] ?? '',
            'plan' => $this->post('plan'),
            'channel' => $this->post('channel'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'teamStid' => L('recruitment.table.members'),
            'money' => L('recruitment.table.budget'),
            'channel' => L('recruitment.table.channel'),
        ];
        $rules = [
            'teamStid' => 'required',
            'money' => 'required|numeric',
            'channel' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('recruitment.table.plan_edit');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'ZPJH' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
                $userNo = $info['orderNo'];
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{id}}', '{{orderNo}}'], [$this->control['name'], $id, $userNo], L('recruitment.table.plan_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => L('recruitment.table.commitAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '招聘计划',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('recruitment.table.addAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('recruitment.table.transmit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('recruitment.table.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('recruitment.table.no_plan');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $mxButton = '';//招聘目标按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
                $mxButton = "
                <span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . $info['id'] . "'})\">" . L('recruitment.table.fromReImport') . "</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">" . L('recruitment.table.del') . "</span>";
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll,
                L('recruitment.table.jobName'),
                L('recruitment.table.peopleNum'),
                L('recruitment.table.expectTime'),
                L('recruitment.table.dutyText'),
                L('recruitment.table.requirements')];
            $total = ['num'=>0];
            foreach ($result['array'] as $val) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $val['id']),
                );
                $recruitment = query('recruitment', " id = '$val[sourceId]'");
                $tr[] = [$this->dominate($dominate), $recruitment['jobName'], $recruitment['num'], $recruitment['arrivalDate'], neirong(html_entity_decode($recruitment['jobText'], ENT_QUOTES)), neirong(html_entity_decode($recruitment['workText'], ENT_QUOTES))];
                $total['num'] += $recruitment['num'];
            }
            $total_tr = [
                2=>$total['num']
            ];
            $audit = query('audit', " targetId = '$info[id]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('recruitment.table.members') => $this->findTeamStName($info['teamStid']),
                        L('recruitment.table.budget') . "(" . static::$unit . ")" => $info['money'],
                        L('recruitment.table.channel') => $info['channel'],
                        L('recruitment.table.startAndEnd') => self::null($info['startDate']) . '至' . self::null($info['endDate']),
                    ),
                    array(
                        L('recruitment.table.programme') => pre(html_entity_decode($info['plan'], ENT_QUOTES)),
                    ),
                    array(
                        L('recruitment.table.text') => pre(html_entity_decode($info['text'], ENT_QUOTES)),
                    ),
                ),
                "系统信息" => array(
                    array(
                        L('recruitment.table.orderNo') => $info['orderNo'],
                        L('recruitment.table.staffDept') => $info['deptName'],
                        L('recruitment.table.prepared') => self::findStaff($info['stid']),
                        L('recruitment.table.createTime') => $info['time'],
                    ),
                    array(
                        L('recruitment.table.commitTime') => self::null($audit['commitTime']),
                        L('recruitment.table.state') => $info['state'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => L('recruitment.table.Objectives'),
                'button' => $mxButton,
                'html' => "
                <div class='purchaseMx'>
                    <form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)) . "</form>
                </div>
                ",
            ]);
            $data['html'] .= $this->detailBlock([
                L('recruitment.table.flow') => auditClass::auditRecord(self::table, $info['id'])
            ]);
            $data['html'] .= <<<eof
<style>
 .spanButton-other{
    width: auto;
    padding: 0 10px;
    margin-left: 0
 }
</style>
eof;

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 添加招聘目标
     * @return bool|string
     */
    public function addMx()
    {
        $html =
            text(array("name" => "orderNo", "title" => L('recruitment.table.orderNo'))) .
            text(array("name" => "jobName", "title" => L('recruitment.table.jobName'))) .
            text(array("name" => "arrivalDate", 'class' => 'width200', 'laydate' => ['range' => '~'], "title" => L('recruitment.table.expectTime') . "-" . L('recruitment.table.expectTime'))) .
            selectMultiple(array("name" => "stid", 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', "title" => L('recruitment.table.stid'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" type='button' class='searchSub' value='" . L('recruitment.table.commit') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('recruitment.table.addMx'), "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加招聘目标
     */
    public function addMxSearch()
    {
        $id = $this->post('id');
        $where = " 1=1 and id not in (select sourceId from `recruitment_plan_detail` where sourceTable = 'recruitment')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
            'jobName' => $this->post('jobName'),
        ];
        $equal = [
            'stid' => $this->post('stid'),
            'state' => '已通过'
        ];
        if ($this->post('arrivalDate')) {
            $timeArr = explode('~', $this->post('arrivalDate'));
            $and .= " and arrivalDate >='{$timeArr[0]}' and arrivalDate <='{$timeArr[1]}'";
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "recruitment",
            "where" => $where,
            'pageNum' => 50,
            "order" => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll,
            L('recruitment.table.orderNo'),
            L('recruitment.table.jobName'),
            L('recruitment.table.needPeople'),
            L('recruitment.table.expectTime'),
            L('recruitment.table.stid')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['jobName'],
                $array['num'],
                $array['arrivalDate'],
                self::findStaff($array['stid']),
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . hidden(array('name' => 'id', 'value' => $id)) . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加招聘需求到招聘计划中
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('recruitment.table.plan_edit');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('recruitment.table.chooseData');
        } else {
            $x = 0;
            foreach ($mxIdArr as $mxId) {
                $recruitment = query('recruitment', " id = '$mxId'");
                $mx = query(self::tableMx, " sourceId = '$mxId'");
                if (!$mx['id']) {
                    //未在招聘计划中
                    $warn = insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => suiji(),
                            'orderId' => $id,
                            'sourceTable' => 'recruitment',
                            'sourceId' => $mxId,
                            'time' => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text = str_replace(['{{staffName}}', '{{rNo}}', '{{orderNo}}'], [$this->control['name'], $recruitment['orderNo'], $info['orderNo']], L('recruitment.table.addData'));
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('recruitment.table.chooseData'));
        }
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = L('recruitment.table.del_target');
                $title = self::page . 'DeleteMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('recruitment.table.del_plan');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('recruitment.table.msg'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除招聘计划
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_permission');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= L('recruitment.table.plan') . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('recruitment.table.del_plan_text')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('recruitment.table.del_plan_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除招聘目标
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_permission');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $recruitment = query('recruitment', " id = '$mx[sourceId]' ");
                $recruitmentPlan = query(self::table, " id = '$mx[orderId]' ");
                if ($recruitmentPlan['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;

                }

                $text .= str_replace(['{{jobName}}', '{{id}}'], [$recruitment['jobName'], $mx['id']], L('recruitment.table.del_target_text_A')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('recruitment.table.del_target_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('recruitment.table.del_target_text'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

